// uni iap

const ProviderType = {
	IAP: 'iap'
};

const IapTransactionState = {
	purchasing: '0', // A transaction that is being processed by the App Store.
	purchased: '1', // A successfully processed transaction.
	failed: '2', // A failed transaction.
	restored: '3', // A transaction that restores content previously purchased by the user.
	deferred: '4' // A transaction that is in the queue, but its final status is pending external action such as Ask to Buy.
};

class Iap {
	_channel = null;
	_channelError = null;
	_productIds = [];
	upResut = null;
	endLoadding = null; // 让支付按钮停止loadding状态使用
	constructor({
		products,
		upResut,
		endLoadding
	}) {
		this._productIds = products;
		this.upResut = upResut;
		this.endLoadding = endLoadding;
		this.init()
			.then(() => {
				this.getProduct()
			})
	}

	init() {
		let _this = this
		return new Promise((resolve, reject) => {
			this.getChannels(
				(channel) => {
					this._ready = true;
					_this._channel = channel
					// _this.restore();
					resolve(channel);

				},
				(err) => {
					// reject(err);
					uni.showModal({
						title: 'init',
						content: e.message,
						showCancel: false
					});
				}
			);
		});
	}
	async pay(productid) {
		let _this = this
		uni.showLoading({
			title: '支付处理中...'
		});
		try {
			const transaction = await this.requestPayment({
				productid: productid,
				manualFinishTransaction: true,
			});

			if (!this.upResut) {
				uni.showToast({
					icon: 'none',
					title: '请初始化上传函数'
				})
				if (this.endLoadding) this.endLoadding();
				return;
			}
			await this.upResut({
				transactionReceipt: transaction.transactionReceipt, // 不可作为订单唯一标识
				transactionIdentifier: transaction.transactionIdentifier,
			},'购买成功')
			// console.log(transaction)
			this.finishTransaction(transaction);
		} catch (e) {
			console.log('支付失败', e);
			if (e.errCode == 2) {
				uni.showToast({
					icon: 'none',
					title: '支付失败,取消支付'
				})
			} else {
				uni.showModal({
					content: e.errMsg,
					showCancel: false
				});
			}
		} finally {
			if (this.endLoadding) this.endLoadding();
			uni.hideLoading();
		}
	}
	async restore() {
		uni.showLoading({
			title: '正在检测已支付且未关闭的订单...'
		});
		let _this = this
		try {
			// 从苹果服务器检查未关闭的订单，可选根据 username 过滤，和调用支付时透传的值一致
			const transactions = await this.restoreCompletedTransactions({});
			if (transactions.length == 0) {
				uni.showToast({
					title: '没有需要恢复的订单'
				});
				return;
			}
			// console.log(transactions)
			for (const transaction of transactions) {
				switch (transaction.transactionState) {
					case IapTransactionState.purchased:
					case IapTransactionState.restored:
						if (_this.upResut) {
							await _this.upResut({
								transactionReceipt: transaction.transactionReceipt, // 不可作为订单唯一标识
								transactionIdentifier: transaction.transactionIdentifier,
							},'恢复购买成功')
							// console.log('成功');
							_this.finishTransaction(transaction);
						}
						break;
					case IapTransactionState.failed:
						// 关闭未支付的订单
						_this.finishTransaction(transaction);
						break;
					default:
						break;
				}
			};
		} catch (e) {
			if (!e) return;
			console.log(e)
			uni.showModal({
				content: e.errMsg || e.message,
				showCancel: false
			});
		}
	}
	getProduct(productIds) {
		return new Promise((resolve, reject) => {
			this._channel.requestProduct(
				productIds || this._productIds,
				(res) => {
					uni.$emit('getIosOriginProduct',res);
					// console.log(res)
					resolve(res);
				},
				(err) => {
					reject(err);
				}
			);
		});
	}

	requestPayment(orderInfo) {
		return new Promise((resolve, reject) => {
			uni.requestPayment({
				provider: 'appleiap',
				orderInfo: orderInfo,
				success: (res) => {
					resolve(res);
				},
				fail: (err) => {
					reject(err);
				}
			});
		});
	}

	restoreCompletedTransactions(username) {
		return new Promise((resolve, reject) => {
			this._channel.restoreCompletedTransactions({
					manualFinishTransaction: true,
					username
				},
				(res) => {
					resolve(res);
				},
				(err) => {
					reject(err);
				}
			);
		});
	}

	finishTransaction(transaction) {
		return new Promise((resolve, reject) => {
			this._channel.finishTransaction(
				transaction,
				(res) => {
					console.log('关闭交易成功')
					resolve(res);
				},
				(err) => {
					console.error('关闭iOS交易失败', err)
					reject(err);
				}
			);
		});
	}

	getChannels(success, fail) {
		if (this._channel !== null) {
			success(this._channel);
			return;
		}

		if (this._channelError !== null) {
			fail(this._channelError);
			return;
		}

		uni.getProvider({
			service: 'payment',
			success: (res) => {
				// console.log(res);
				this._channel = res.providers.find((channel) => {
					return channel.id === 'appleiap';
				});

				if (this._channel) {
					success(this._channel);
				} else {
					this._channelError = {
						errMsg: 'paymentContext:fail iap service not found'
					};
					fail(this._channelError);
				}
			}
		});
	}

	get channel() {
		return this._channel;
	}
}

export {
	Iap,
	IapTransactionState,
};